﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using MixScript.DBService;
using MixScript.BLL;

namespace MixScript.BLL.MM
{
    public class cGRN : cBaseBLL
    {
        private string sgrnno;

        public string sGRNno
        {
            get { return sgrnno; }
            set { sgrnno = value; }
        }
        private string smodul;

        public string sModul
        {
            get { return smodul; }
            set { smodul = value; }
        }
        private string spo;

        public string sPO
        {
            get { return spo; }
            set { spo = value; }
        }
        private string ssupp;

        public string sSupp
        {
            get { return ssupp; }
            set { ssupp = value; }
        }

        private string sdelno;

        public string sDelno
        {
            get { return sdelno; }
            set { sdelno = value; }
        }
        private string sWrhid;
        public string swrhid
        {
            get { return sWrhid; }
            set { sWrhid = value; }
        }
        private string sreqdept;

        public string sReqdept
        {
            get { return sreqdept; }
            set { sreqdept = value; }
        }
        private DateTime dtcreated;

        public DateTime dtCreated
        {
            get { return dtcreated; }
            set { dtcreated = value; }
        }


        public cGRN()
        {

        }
        public string getPONO(string grnid)
        {
            string sret = "";
            try
            {
                sret = Dbserver.ExecuteScalar("select top 1 ponum from tb_grtrx where grid='"+grnid+"'").ToString();
                return sret;
                
            }
            catch (Exception)
            {

                return sret;
            }
        }
        public string getGRNno()
        {
            return new cDBHelper().genId("M", "GRNID");
        }
        public bool getgrnlist(ref DataTable dt, string spono, string scustid, DateTime tgl1, DateTime tgl2, string stblname)
        {
            try
            {
                string ssql = "select * from " + stblname + " where 1=1  ";
                if (spono.Trim() != string.Empty)
                {
                    ssql += "and grid='" + spono + "' ";
                }

                if (scustid.Trim() != string.Empty)
                {
                    ssql += "and codfbpid='" + scustid + "' ";
                }
                if (tgl1.Year > 2001 && tgl2.Year > 2001)
                {
                    ssql += "and grdate between '" + tgl1.ToString("yyyy-MM-dd 00:00:00") + "' and '" + tgl2.ToString("yyyy-MM-dd 23:59:59") + "'";
                }

                dt = Dbserver.ExecuteQuery(ssql, stblname);

                //  getInquiry(ref dt, new string[] { pono }, "vw_porpt", out s);
                return dt.Rows.Count > 0;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


        public bool saveGRN(DataTable dt, string sloginid, out string sout,bool isRawMat)
        {
            try
            {
                sout = "";
                DataTable dt2 = new DataTable();
                DataTable dtdtl = new DataTable();
                DataTable dtsliphdr = new DataTable();
                DataTable dtslipdtl = new DataTable();
                getTableStructure(ref dt2, "tb_grtrx");
                getTableStructure(ref dtdtl, "tb_grtrxdtl");
                getTableStructure(ref dtsliphdr, "accsliphdr");
                getTableStructure(ref dtslipdtl, "accslipdet");
                string smodulname = "";

                sGRNno = getGRNno() + "/" + getServerTime().ToString("MM-yyyy");
                foreach (DataRow drr in dt.Rows)
                {
                    if (drr["iorfno"].ToString() != string.Empty)
                    {
                       
                        DataRow drdtl = dtdtl.NewRow();
                        DataRow drslipdet = dtslipdtl.NewRow();
                        //drdtl["delno"] = delno;
                        //drdtl["cuid"] = drr["cuid"];
                        drdtl["grid"] = sGRNno;
                        drdtl["iorfno"] = drr["iorfno"];
                        drdtl["grdesc"] = drr["grdesc"];
                        drdtl["matid"] = drr["itno"];
                        drdtl["unitid"] = drr["unmsns"];
                        drdtl["qty"] = drr["ioqt"];
                        dtdtl.Rows.Add(drdtl);

                        //smodulname = spo + " - " + Dbserver.ExecuteScalar("select top 1 bpidnm from vw_bommodulname where itno='" + drr["itno"] + "'"); // drr["itnm"];
                        smodulname = spo + " - " + Dbserver.ExecuteScalar("select top 1 bpidnm from vw_joid_module_v where codfbpid='" + sreqdept + "'"); // drr["itnm"];

                        DataTable dtaccc = Dbserver.ExecuteQuery("select top 1  * from tb_materialmapping where matno='"+drr["itno"]+"' and typ='GRN'", "mapping");

                        if (dtaccc.Rows.Count == 0)
                            throw new Exception("Material Mapping Not Found. Material ID: " + drr["itno"].ToString());
                        DataRow dracc = dtaccc.Rows[0];

                        string sacc = dracc["acctnum"].ToString(); // Dbserver.ExecuteScalar("select fk_modulid from tb_mappingmodulmaterial where fk_materialid='" + drr["itno"] + "'").ToString();
                        string sprice = Dbserver.ExecuteScalar("select top 1 orup from vw_joid_purchase_unit_price_v where itno='" + drr["itno"] + "' and aptodt>= getdate()" ).ToString();
                        decimal dcprice = 0;
                        if (sprice != string.Empty)
                            dcprice = decimal.Parse(sprice);

                        drslipdet["id"] = new cDBHelper().genIDCommit("SLIPDTLID");
                        drslipdet["acctnum"] = sacc;
                        drslipdet["desc"] = Dbserver.ExecuteScalar("select top 1 bpidnm from vw_joid_supplier_v where codfbpid='"+ssupp+"'");// drr["itnm"];
                        drslipdet["dbcd"] = "C";
                        drslipdet["currency"] = "IDR";
                        drslipdet["kurs"] = "pajak";
                        drslipdet["rate"] = "1";
                        drslipdet["amount"] = dcprice * decimal.Parse(drr["ioqt"].ToString());
                        drslipdet["valconvert"] = drslipdet["amount"];// "1";
                        drslipdet["so_id"] = "1";
                        //drslipdet["fg_id"] = "1";
                        drslipdet["invoice"] = "";
                        drslipdet["process"] = 0;
                        //drslipdet["subsidiary"] = sSupp.Trim();

                        dtslipdtl.Rows.Add(drslipdet);
                        
                

                    }
                }

                //Inventory D
                double totAmount = 0;

               
                foreach (DataRow drrr in dtslipdtl.Rows)
                {
                    double dtemp = 0;
                    if (double.TryParse(drrr["amount"].ToString(), out dtemp))
                    {
                        totAmount += dtemp;
                       
                    }
                    
                }

                DataRow drInv = dtslipdtl.NewRow();
                if (isRawMat)
                {
                    drInv["id"] = new cDBHelper().genIDCommit("SLIPDTLID");
                    drInv["acctnum"] = "10107     ";//kata pak fatah;
                    drInv["desc"] = smodulname;//spo + " - " + Dbserver.ExecuteScalar("select top 1 bpidnm from vw_bommodulname where itno='" + ssupp + "'"); // drr["itnm"];
                    drInv["dbcd"] = "D";
                    drInv["currency"] = "IDR";
                    drInv["kurs"] = "pajak";
                    drInv["rate"] = "1";
                    drInv["amount"] = totAmount;
                    drInv["valconvert"] = totAmount;//drslipdet["amount"];// "1";
                    drInv["so_id"] = "1";
                    //drslipdet["fg_id"] = "1";
                    drInv["invoice"] = "";
                    drInv["process"] = 0;
                    //drslipdet["subsidiary"] = sSupp.Trim();


                    dtslipdtl.Rows.Add(drInv);

                }
                //master
                DataRow dr = dt2.NewRow();
                dr["wrhid"] = swrhid;

                //dr["delno"] = delno;
                dr["grid"] = sGRNno;
                //dr["mdltyp"] = sSection;
                dr["suppid"] = sSupp;
                dr["ponum"] = spo;
                dr["reqdept"] = sReqdept;
                dr["delno"] = sDelno;

                dr["usergr"] = sloginid;
                dr["grdate"] = getServerTime();


                new cDBHelper().genIDCommit("M", "GRNID");
                dt2.Rows.Add(dr);
                int nret = 0;
                //=posting acc
                dr = dtsliphdr.NewRow();
                dr["kd_cmpy"] = "01";
                dr["slipdate"] = getServerTime();
                dr["sliptype"] = "5";
                dr["slipCode"] = "CRMI1";


                dr["slipcurr"] = "IDR";
                dr["slipdesc"] = "Good Receiving Notes";
                dr["posting"] = 1;
                dr["forex"] = 0;
                dr["transfer"] = 0;
                dr["slipNum"] = Int32.Parse(new cDBHelper().genId("SLIPID")).ToString().PadLeft(7, '0');
                dr["slipid"] = new cDBHelper().genIDCommit("SLIPID");
                dr["matref"] = sGRNno;


                dtsliphdr.Rows.Add(dr);

                if (dtdtl.Rows.Count > 0)
                {



                    if (isRawMat)
                    {
                        if (!posting2Accounting(dtsliphdr, dtslipdtl, sGRNno, out sout))
                            return false;
                    }

                    if (Dbserver.openConn())
                    {
                        nret = Dbserver.SqlUpdate(dt2, "tb_grtrx", out sout);
                        if (nret > 0)
                        {
                            nret = Dbserver.SqlUpdate(dtdtl, "tb_grtrxdtl", out sout);
                            Dbserver.CommitAndCloseConn();
                        }
                        else
                        {
                            Dbserver.ForceRollBackNClose();
                            return false;
                        }
                    }
                    else
                    {
                        sout = "Could not Open Database";
                        return false;

                    }
                    //Dbserver.SqlUpdate();

                    return nret > 0;
                }
                else
                {
                    sout = "Detail is empty";
                    return false;
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}
